<?php

namespace Modules\Visitor\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Cache;
use Auth;
use Validator;
use ThrowException;
use Modules\Visitor\Entities\Visitor;

use Agent;
use DB;

class VisitorController extends Controller
{
    public function store(Request $req)
    {
        $rule = [
            'device' => ['array']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $info = $req->all();

        $ip = $req->getClientIp();

        $visitor = (new Visitor())->init($ip);

        $visitor->app = $req->input('app');

        if ($req->input('origin')) {
            $visitor->origin = [
                'title' => getTitle($req->origin),
                'url' => $req->origin
            ];
        }

        if ($req->input('scene_id')) {
            $visitor->origin = [
                'title' => @v(config('scene')[$req->scene_id])
            ];
        }

        $user = null;
        if ($req->input('share_id')) {
            $user = User::getEntity(intVal($req->share_id), false);
            if ($user) {
                $visitor->share_by = [
                    'name' => $user->name,
                    'headimg' => $user->headimg,
                    'type' => 'miniapp',
                    'user' => [
                        'name' => $user->name,
                        'id' => $user->id,
                        'uuid' => $user->uuid
                    ]
                ];
            }
        }

        if (Auth::user()) {
            $user = Auth::user();
            $visitor->user = [
                'id' => $user->id,
                'uuid' => $user->uuid,
                'name' => $user->name,
                'headimg' => $user->headimg
            ];
            $visitor->user_id = $user->id;
        }

        if ($req->input('wechat')) {
            $visitor->wechat = [
                'nickname' => $req->input('wechat.nickname'),
                'headimgurl' => $req->input('wechat.headimgurl'),
                'gender' => $req->input('wechat.gender')
            ];
            $visitor->wechat_sex = $req->input('wechat.gender');
        }

        if ($req->input('page')) {
            $visitor->page = $req->input('page');

            if ($req->input('page')) {
                // 根据uuid查类型
                $type = $req->input('page.type');
                $uuid = $req->input('page.uuid');
                
                $visitor->page = @array_merge($visitor->page, [
                    'type_text' => $visitor->mapTitle($type)
                ]);
                
            }
        }


        $visitor->client = [
            'type' => @v($info['client']['type']),
            'version' => @v($info['client']['version'])
        ];

        $visitor->device = [
            'type' => Agent::device(),
            'width' => @v($info['device']['width']),
            'height' => @v($info['device']['height']),
            'is_wifi' => @v($info['device']['is_wifi'])
        ];

        $platform = Agent::platform();
        $visitor->platform = [
            'type' => $platform,
            'version' => Agent::version($platform)
        ];

        $browser = Agent::browser();
        $visitor->browser = [
            'type' => $browser,
            'version' => Agent::version($browser)
        ];

        $visitor->createAll();

        // 按ip存储独立访客
        // $this->storeUnionVisitor($visitor);

        // if ($req->input('page.type') !== 'login')
        //     Auth::requireLoginUser();

        return [
        ];
    }

    public function storeUnionVisitor($visitor)
    {
        // 为租户存储
        if (!is_null($visitor->tenant_id)) {
            $collection = date('Y_m_d_').$visitor->tenant_id;
            $db = DB::connection('mongodb')->collection($collection);

            if (!$db->where('ip', $visitor->ip)->first()) {
                $db->insert($visitor->toArray());
            }
        }

        // 为平台存储
        $collection = date('Y_m_d_').'0';
        $db = DB::connection('mongodb')->collection($collection);
        if (!$db->where('ip', $visitor->ip)->first()) {
            $db->insert($visitor->toArray());
        }
    }

    public function setShareId(Request $req) 
    {
        $rule = [
            'share_id' => ['string', 'required'],
            'name' => ['string'],
            'headimg' => ['string'],
            'type' => ['string']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $cache = $req->all();
        $cache['shared_at'] = date('Y-m-d H:i:s');

        $user = Auth::user();
        if ($user) {
            $cache['user'] = [
                'name' => $user->name,
                'id' => $user->id,
                'uuid' => $user->id,
            ];
        }

        Cache::put('share_id_'.$req->share_id, $cache, 2000);

        return [];
    }
}
